//
//  YouMengPushDelegate.swift
//  GuangLingWuLian
//
//  Created by 宋海胜 on 2020/11/2.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit

let YoumengKeys = "5f97e7f01c520d30739a1f0e"

// 友盟推送设置
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func youmengPush(_ application: UIApplication, _ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        
        // UMConfigure 通用设置，请参考SDKs集成做统一初始化。
        UMConfigure.initWithAppkey(YoumengKeys, channel: nil)
        
        // Push组件基本功能配置
        let entity: UMessageRegisterEntity = UMessageRegisterEntity()
        // type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
        entity.types = Int(UMessageAuthorizationOptions.badge.rawValue | UMessageAuthorizationOptions.sound.rawValue | UMessageAuthorizationOptions.alert.rawValue)
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        }
        UMessage.registerForRemoteNotifications(launchOptions: launchOptions, entity: entity) { (granted, error) in
            if granted {
                // 用户选择了接收Push消息
                print("用户选择了接收Push消息")
            } else {
                // 用户拒绝接收Push消息
                print("用户拒绝接收Push消息")
            }
        }
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        //....TODO
        //过滤掉Push的撤销功能，因为PushSDK内部已经调用的completionHandler(UIBackgroundFetchResultNewData)，
        //防止两次调用completionHandler引起崩溃
        if (userInfo["aps.recall"] != nil) {
            completionHandler(UIBackgroundFetchResult.newData)
        }
    }
    
    
    // 打印设备注册码，需要在友盟测试设备上自己添加deviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        UMessage.registerDeviceToken(deviceToken)
        // d1990eaa241b84488c13d923daf94f2a634aee749be9774754c7e0bc89597697
        print("deviceToken————>>>\(deviceToken) \n\(TokenGet().getTokenStr(deviceToken))")
        
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }
     
    
    
    // iOS10新增：处理前台收到通知的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("10以上前台");
        let userInfo: Dictionary = notification.request.content.userInfo
        
        if ((notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!) {
            
            // 应用处于前台时的远程推送接受
            // 关闭U-Push自带的弹出框
//            UMessage.setAutoAlert(false)
//            //（前台、后台）的消息处理
//            UMessage.didReceiveRemoteNotification(userInfo)
        } else {
            // 应用处于前台时的本地推送接受
        }
        NotificationCenter.default.post(name: NSNotification.Name.Noti_PushMsg, object: nil, userInfo: nil)
        // 当应用处于前台时提示设置，需要哪个可以设置哪一个
        completionHandler(UNNotificationPresentationOptions(rawValue: UNNotificationPresentationOptions.sound.rawValue | UNNotificationPresentationOptions.badge.rawValue | UNNotificationPresentationOptions.alert.rawValue))
    }
    
    // iOS10新增：处理后台点击通知的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("10以上后台");
        let userInfo: Dictionary = response.notification.request.content.userInfo
        
        if ((response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!) {
            
            // 应用处于后台时的远程推送接受
            //（前台、后台）的消息处理
//            UMessage.didReceiveRemoteNotification(userInfo)
            if (userInfo.count > 0) {
                //消息处理
                print("跳转到你想要的");
            } else {
                // 应用处于后台时的本地推送接受
            }
        }
        NotificationCenter.default.post(name: NSNotification.Name.Noti_PushMsg, object: nil, userInfo: nil)
    }
}

extension Notification.Name {
    
    /// 有推送消息
    static let Noti_PushMsg = Notification.Name("Noti_PushMsg")
}
